<template>
  <el-dialog 
    v-model="visible" 
    :title="`司机车辆信息详情 - ${driverInfo.nickname || driverInfo.username}`" 
    :destroy-on-close="true" 
    width="90%" 
    draggable 
    append-to-body
    :close-on-click-modal="false"
  >
    <div class="vehicle-detail-container">
      <!-- 司机基本信息 -->
      <el-card class="driver-info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>司机基本信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="用户名">{{ driverInfo.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ driverInfo.nickname || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ driverInfo.phone }}</el-descriptions-item>
          <el-descriptions-item label="身份证">{{ driverInfo.idCard || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ driverInfo.age || '未填写' }}岁</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ driverInfo.sex === 1 || driverInfo.sex === '1' ? '男' : driverInfo.sex === 2 || driverInfo.sex === '2' ? '女' : '未知' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 车辆信息表格 -->
      <el-card class="vehicle-table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>车辆信息列表</span>
            <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
              刷新数据
            </el-button>
          </div>
        </template>
        
        <ProTable
          ref="proTableRef"
          :columns="columns"
          :request-api="getTableList"
          :init-param="{ userId: currentDriverId }"
          row-key="vehicleId"
          :pagination="true"
          :tool-button="['refresh']"
        >
          <!-- 监控文件记录展开行 -->
          <template #expand="{ row }">
            <div class="expand-content">
              <h4>作业记录</h4>
              <el-table 
                :data="row.monitorFileRecords" 
                stripe 
                style="width: 100%"
                :default-sort="{ prop: 'createTime', order: 'descending' }"
              >
                <el-table-column prop="originalFilename" label="原始文件名" width="" show-overflow-tooltip />
                <el-table-column prop="newFilename" label="新文件名" width="200" show-overflow-tooltip />
                <el-table-column prop="fileUrl" label="文件预览" width="120">
                  <template #default="{ row: fileRow }">
                    <div v-if="isImageFile(fileRow.originalFilename)" class="image-preview">
                      <AuthenticatedImage
                        :src="fileRow.fileUrl"
                        :style="{
                          width: '60px',
                          height: '40px',
                          borderRadius: '4px',
                          cursor: 'pointer'
                        }"
                        fit="cover"
                      />
                    </div>
                    <span v-else class="non-image-text">非图片文件</span>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="processStatus" label="处理状态" width="100">
                  <template #default="{ row: fileRow }">
                    <el-tag :type="fileRow.processStatus === '1' ? 'success' : 'warning'">
                      {{ fileRow.processStatus === '1' ? '已处理' : '未处理' }}
                    </el-tag>
                  </template>
                </el-table-column> -->
                <el-table-column prop="fileTag" label="文件标签" width="200" show-overflow-tooltip />
                <el-table-column prop="carNumber" label="车牌号" width="200" />
                <el-table-column prop="processTime" label="处理时间" width="180" />
                <!-- <el-table-column prop="createTime" label="创建时间" width="180" /> -->
                <!-- <el-table-column label="操作" width="120">
                  <template #default="{ row: fileRow }">
                    <el-button type="primary" link size="small" @click="viewOcrResult(fileRow)">
                      查看OCR结果
                    </el-button>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </template>
        </ProTable>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- OCR结果查看对话框 -->
  <el-dialog
    v-model="ocrDialogVisible"
    title="OCR识别结果"
    width="60%"
    :destroy-on-close="true"
    append-to-body
  >
    <div class="ocr-result-container">
      <el-card>
        <template #header>
          <span>文件信息</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="原始文件名">{{ currentOcrFile?.originalFilename }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ currentOcrFile?.carNumber }}</el-descriptions-item>
          <el-descriptions-item label="文件标签">{{ currentOcrFile?.fileTag || '无' }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentOcrFile?.processTime }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <el-card style="margin-top: 20px;">
        <template #header>
          <span>OCR识别结果</span>
        </template>
        <div class="ocr-content">
          <pre>{{ formatOcrResult(currentOcrFile?.carNumberRes || '') }}</pre>
        </div>
      </el-card>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import AuthenticatedImage from '../../statisticsData/components/AuthenticatedImage.vue';
import type { ColumnProps, ProTableInstance } from '@/components/ProTable/interface';
import { getDriverVehicleInfo } from '@/api/modules/datainfo/driverUser';
import type { UserInfo, VehicleDetailInfo, VehicleDetailQuery, MonitorFileRecord } from '@/api/types/datainfo/driverUser';

defineOptions({
  name: 'VehicleDetail'
});

const visible = ref(false);
const loading = ref(false);
const ocrDialogVisible = ref(false);
const proTableRef = ref<ProTableInstance>();
const driverInfo = ref<UserInfo>({} as UserInfo);
const currentOcrFile = ref<MonitorFileRecord | null>(null);
const currentDriverId = ref<number | undefined>(undefined);

// 判断是否为图片文件
const isImageFile = (fileName: string) => {
  if (!fileName) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
  return imageExtensions.some(ext => fileName.toLowerCase().endsWith(ext));
};

// 表格列配置
const columns: ColumnProps<VehicleDetailInfo>[] = [
  { type: 'expand', width: 80 },
  { type: 'index', label: '序号', width: 80 },
  { prop: 'vehicleNumber', label: '车辆编号', width: 120 },
  { prop: 'vehicleTitle', label: '车辆名称', width: 150 },
  { prop: 'departmentName', label: '所属部门', width: 150 },
  { prop: 'scheduleName', label: '班次名称', width: 150 },
  { 
    prop: 'scheduleType', 
    label: '班次类型', 
    width: 120,
    render: (scope) => {
      const typeMap: { [key: string]: string } = {
        '2001001': '单班制',
        '2001002': '二班制', 
        '2001003': '三班制'
      };
      return typeMap[scope.row.scheduleType] || scope.row.scheduleType;
    }
  },
  { 
    prop: 'scheduleTime1', 
    label: '班次时间', 
    width: 200,
    render: (scope) => {
      const { scheduleTime1, scheduleTime2, scheduleTime3 } = scope.row;
      const times = [scheduleTime1, scheduleTime2, scheduleTime3].filter(time => time && time.trim() !== '');
      return times.join(' / ') || '未设置';
    }
  },
  {
    prop: 'monitorFileRecordCount',
    label: '作业工作数量',
    width: 120,
    render: (scope) => {
      // 调试信息
      console.log('Vehicle row data:', scope.row);
      
      // 使用monitorFileRecordCount字段，如果不存在则计算数组长度
      const count = scope.row.monitorFileRecordCount ?? scope.row.monitorFileRecords?.length ?? 0;
      
      // 调试信息
      console.log('File count calculation:', {
        monitorFileRecordCount: scope.row.monitorFileRecordCount,
        arrayLength: scope.row.monitorFileRecords?.length,
        finalCount: count
      });
      
      return h('el-tag', { type: count > 0 ? 'success' : 'info' }, count.toString());
    }
  }
];

// 获取表格列表数据
const getTableList = (params: VehicleDetailQuery) => {
  try {
    // 确保传递正确的userId参数
    const requestParams = {
      ...params,
      driverId: currentDriverId.value || params.userId
    };
    
    console.log('VehicleDetail - API request params:', requestParams);
    
    // 添加响应处理以查看实际数据
    return getDriverVehicleInfo(requestParams).then(response => {
      console.log('VehicleDetail - API response:', response);
      if (response.data && response.data.rows) {
        console.log('VehicleDetail - Rows data:', response.data.rows);
        // 检查每行数据的结构
        response.data.rows.forEach((row, index) => {
          console.log(`VehicleDetail - Row ${index} structure:`, Object.keys(row));
          console.log(`VehicleDetail - Row ${index} monitorFileRecords:`, row.monitorFileRecords);
          console.log(`VehicleDetail - Row ${index} monitorFileRecordCount:`, row.monitorFileRecordCount);
        });
      }
      return response;
    });
  } catch (error) {
    console.error('获取车辆信息失败:', error);
    ElMessage.error('获取车辆信息失败');
    throw error;
  }
};

// 刷新数据
const refreshData = () => {
  if (currentDriverId.value) {
    console.log('VehicleDetail - Refreshing data for driver ID:', currentDriverId.value);
    proTableRef.value?.getTableList();
    ElMessage.success('数据刷新成功');
  } else {
    ElMessage.warning('无法刷新，缺少司机ID');
  }
};

// 查看OCR结果
const viewOcrResult = (fileRow: MonitorFileRecord) => {
  currentOcrFile.value = fileRow;
  ocrDialogVisible.value = true;
};

// 格式化OCR结果
const formatOcrResult = (ocrResultStr: string) => {
  if (!ocrResultStr) return '暂无OCR结果';
  
  try {
    const ocrResult = JSON.parse(ocrResultStr);
    return JSON.stringify(ocrResult, null, 2);
  } catch (error) {
    return ocrResultStr;
  }
};

// 接收父组件传过来的参数
const acceptParams = (driver: UserInfo, driverId?: number) => {
  driverInfo.value = driver;
  currentDriverId.value = driverId || driver.id;
  
  console.log('VehicleDetail - Received driver info:', driver);
  console.log('VehicleDetail - Using driver ID:', currentDriverId.value);
  
  visible.value = true;
  
  // 延迟一点再加载数据，确保组件已经正确初始化
  setTimeout(() => {
    proTableRef.value?.getTableList();
  }, 100);
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.vehicle-detail-container {
  .driver-info-card {
    margin-bottom: 20px;
  }
  
  .vehicle-table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .expand-content {
    padding: 20px;
    background-color: #f8f9fa;
    
    h4 {
      margin: 0 0 15px 0;
      color: #333;
      font-weight: 600;
    }
    
    .image-preview {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .non-image-text {
      color: #909399;
      font-size: 12px;
    }
  }
  
  .ocr-result-container {
    .ocr-content {
      pre {
        background-color: #f5f7fa;
        padding: 15px;
        border-radius: 4px;
        white-space: pre-wrap;
        word-wrap: break-word;
        max-height: 400px;
        overflow-y: auto;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        line-height: 1.5;
      }
    }
  }
}
</style>